package website.lucaswork.survey.mvc.validators;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ImageFile.ImageFileValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface ImageFile {

    String message() default "The uploaded file is not a valid image file";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    public class ImageFileValidator implements ConstraintValidator<ImageFile, MultipartFile> {

        @Override
        public void initialize(ImageFile constraintAnnotation) {
        }

        @Override
        public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
            if (value == null || value.isEmpty()) {
                return true;
            }
            return value.getContentType().startsWith("image");
        }
    }
}
